import React, { useState } from 'react';
import { useHistory } from 'umi';
import { useModel } from '@@/plugin-model/useModel';
import { UploadOutlined } from '@ant-design/icons';
import { Card, Spin, Form, Input, Button, Alert, Upload, Avatar, message, Checkbox } from 'antd';
import style from './style.module.less';
import { apiAccountEditAvatar, apiAccountEditInfo, apiAccountEditPass } from '@/api/account.api';
import { useRequest, useTimeout } from 'ahooks';
import { history } from '@@/core/history';
import { stringify } from "querystring";

export default () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const history = useHistory();
  const {
    run: editInfo,
    error: editError,
    loading: editLoading,
  } = useRequest(apiAccountEditInfo, { manual: true });

  const {
    run: passInfo,
    error: passError,
    loading: passLoading,
  } = useRequest(apiAccountEditPass, {
    manual: true,
    onSuccess: (result) => {
      if (result.status) {
        message.success('密码修改成功,即将跳转到登录页面。');
        setTimeout(() => {
          history.replace({
            pathname: '/login',
          });
        }, 1000);
      }
    }
  });

  const [previewAvatar, setPreviewAvatar] = useState<string>();

  if (!initialState) {
    return <Spin/>;
  }
  const { userinfo } = initialState;

  // 修改头像
  const previewAvatarImage = async (file: any) => {
    const data: string = window.URL.createObjectURL(file.file.originFileObj);

    setPreviewAvatar(data);
  };

  // 上传头像
  const uploadAvatar = async ({ file }: { file: File }) => {
    apiAccountEditAvatar(file).then(({ data }) => {

      setInitialState({
        ...initialState,
        userinfo: {
          avatar: data.src,
          ...userinfo,
        },
      });
    }).catch(msg => {
      message.error(msg);
    });
  };

  return <Card>
    <div className={style.view}>
      <div className={style.left}>
        <Form layout={'vertical'} initialValues={userinfo} onFinish={editInfo}>
          {editError && <Alert message={editError}
                               showIcon
                               type={'error'}
                               style={{ marginBottom: 20 }}/>}

          <Form.Item
            label={'称呼'}
            name={'nickname'}
            rules={[
              {
                required: true,
                message: '请输入称呼',
              },
            ]}
          >
            <Input/>
          </Form.Item>

          <Form.Item
            label={'邮箱'}
            name={'email'}
            rules={[
              {
                required: true,
                message: '请输入你的邮箱',
              },
              {
                type: 'email',
                message: '请输入正确的邮箱格式',
              },
            ]}
          >
            <Input/>
          </Form.Item>

          <Form.Item
            label={'联系手机'}
            name={'phone'}
          >
            <Input/>
          </Form.Item>

          <Button type={'primary'} loading={editLoading} htmlType={'submit'}>更新基本信息</Button>
        </Form>


        <Form layout={'vertical'} style={{marginTop: 20}} onFinish={(e) => passInfo(e as any)}>
          {!passError && <Alert type={'warning'}
                  showIcon
                  style={{ marginBottom: 20 }}
                  message={'温馨提示'}
                  description={'密码修改成功后需要重新登录。'}/>}

          {passError && <Alert message={passError}
                               showIcon
                               type={'error'}
                               style={{ marginBottom: 20 }}/>}

          <Form.Item
            label={'原登录密码'}
            name={'old'}
            rules={[
              {
                required: true,
                message: '请输入原登录密码',
              },
            ]}
          >
            <Input type={'password'}/>
          </Form.Item>

          <Form.Item
            label={'新的登录密码'}
            name={'new'}
            rules={[
              {
                required: true,
                message: '请输入新的登录密码',
              },
            ]}
          >
            <Input type={'password'}/>
          </Form.Item>

          <Form.Item
            label={'确认登录密码'}
            name={'new2'}
            dependencies={['new']}
            rules={[
              {
                required: true,
                message: '二次密码不一致',
              },
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('new') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('二次密码不一致');
                },
              }),
            ]}
          >
            <Input type={'password'}/>
          </Form.Item>

          <Button type={'primary'} loading={passLoading} htmlType={'submit'}>修改密码</Button>

        </Form>
      </div>

      {/* 右侧 */}
      <div className={style.right}>
        <Form.Item label={'头像'}>
          <div className={style.avatar}>
            <Avatar src={previewAvatar ?? userinfo?.avatar} size={144}/>
          </div>

          <Upload
            name="avatar"
            listType="picture"
            showUploadList={false}
            onChange={previewAvatarImage}
            customRequest={uploadAvatar}
          >
            <Button>
              <UploadOutlined/> 更换头像
            </Button>
          </Upload>
        </Form.Item>
      </div>
    </div>
  </Card>;
}
